from django.db import models
from fuguang.utils.models import BaseModel
# Create your models here.
from users.models import UserModel
from course.models import CourseModel

class OrdersModel(BaseModel):
    STATUS_CHOICES = {
        (0, '未支付'),
        (1, '已支付'),
        (2, '已取消'),
        (3, '已超时'),
    }
    PAY_CHOICES = {
        (0, '支付宝'),
        (1, '微信'),
        (2, '余额'),
    }
    total_price = models.DecimalField(max_digits=8, decimal_places=2, default=0, verbose_name="订单总价")
    real_price = models.DecimalField(max_digits=8, decimal_places=2, default=0, verbose_name="实付金额")
    order_number = models.CharField(max_length=64, verbose_name="订单号")
    order_status = models.SmallIntegerField(choices=STATUS_CHOICES, default=0, verbose_name="订单状态")
    pay_type = models.SmallIntegerField(choices=PAY_CHOICES, default=0, verbose_name='支付方式')
    order_desc = models.TextField(null=True, blank=True, max_length=300, verbose_name="订单描述")
    pay_time = models.DateTimeField(null=True, blank=True, verbose_name="支付时间")
    credit = models.IntegerField(default=0, null=True, blank=True, verbose_name="积分")
    user = models.ForeignKey(UserModel, related_name="user_orders", on_delete=models.DO_NOTHING, db_constraint=False,
                             verbose_name="用户")

    def coupon(self):
        # 外键关联查询优惠券信息    获取当前优惠券信息
        coupon_related = self.to_coupon.first()
        # 拼接优惠券信息
        if coupon_related:
            return {
                "id": coupon_related.coupon.id,
                "name": coupon_related.coupon.name,
                "sale": coupon_related.coupon.sale,
                "discount": coupon_related.coupon.discount,
                "condition": coupon_related.coupon.condition
            }
        return {}

    class Meta():
        db_table = "fg_order"
        verbose_name_plural = "订单记录表"

    def __str__(self):
        return "%s 总价：%s ,实付金额：%s" % (self.name, self.total_price, self.real_price)



# 订单详情表
class OrdersDetailModel(BaseModel):
    order = models.ForeignKey(OrdersModel,related_name="order_detail",on_delete=models.CASCADE,db_constraint=False,verbose_name="订单")
    course = models.ForeignKey(CourseModel,related_name="order_detail",on_delete=models.DO_NOTHING,db_constraint=False,verbose_name="课程")
    price = models.DecimalField(max_digits=8,decimal_places=2,verbose_name='课程原价')
    real_price = models.DecimalField(max_digits=8,decimal_places=2,verbose_name='优惠价格')
    discount_name = models.CharField(max_length=100,default="",verbose_name="优惠类型")
    class Meta():
        db_table = "fg_order_course"
        verbose_name_plural = "订单详情"
    def __str__(self):
        return self.course.name

